import apis from "./selectApi";

const { queryByName, queryByOrg } = apis;

export default {
  namespace: "personSelect",
  state: {
    loading: false,
    pageIndex: 1,
    pageSize: 5,
    data: [],
    content: "",
    orgCode: "",
    totalCount: 0,
    totalPage: 0,
    query: "name"
  },
  effects: {
    *queryByName({ payload }, { call, put }) {
      yield put({ type: "triggerLoading", payload: true });
      const { data = [], totalPage = 0, totalCount = 0 } = yield call(
        queryByName,
        { content: payload || "" }
      );

      yield put({ type: "saveData", payload: { data, totalPage, totalCount } });
      yield put({ type: "triggerLoading", payload: false });
      yield put({ type: "changeQuery", payload: "name" });
      yield put({
        type: "saveFilter",
        payload: { content: payload || "", pageIndex: 1 }
      });
    },
    *queryByOrg({ payload }, { call, put }) {
      yield put({ type: "triggerLoading", payload: true });
      const { data = [], totalPage = 0, totalCount = 0 } = yield call(
        queryByOrg,
        { orgCode: payload }
      );
      yield put({ type: "saveData", payload: { data, totalPage, totalCount } });
      yield put({ type: "triggerLoading", payload: false });
      yield put({ type: "changeQuery", payload: "org" });
      yield put({
        type: "saveFilter",
        payload: { orgCode: payload || "", pageIndex: 1 }
      });
    },
    *query({ payload }, { call, put, select }) {
      const queryWay = yield select(({ personSelect: { query } }) => query);
      let params;
      let resData;
      yield put({ type: "triggerLoading", payload: true });
      if (queryWay === "name") {
        const contentCache = yield select(
          ({ personSelect: { content } }) => content
        );
        params = { content: contentCache, pageIndex: payload };
        resData = yield call(queryByName, params);
      } else {
        const orgCodeCache = yield select(
          ({ personSelect: { orgCode } }) => orgCode
        );
        params = { orgCode: orgCodeCache, pageIndex: payload };
        resData = yield call(queryByOrg, params);
      }
      const { data, totalPage, totalCount } = resData;
      yield put({ type: "saveData", payload: { data, totalPage, totalCount } });
      yield put({ type: "triggerLoading", payload: false });
      yield put({ type: "saveFilter", payload: { pageIndex: payload } });
    }
  },
  reducers: {
    saveData: (state, { payload }) => ({ ...state, ...payload }),
    saveFilter: (state, { payload }) => ({ ...state, ...payload }),
    changeQuery: (state, { payload }) => ({ ...state, query: payload }),
    triggerLoading: (state, { payload }) => ({ ...state, loading: payload })
  }
};
